"use client";

import { useEffect, useState } from "react";
import Link from "next/link";
import {
  Card,
  CardContent,
  CardDescription,
  CardHeader,
  CardTitle,
} from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { Calendar, User, Tag } from "lucide-react";
import { API_ENDPOINTS, apiRequest } from "@/lib/api";
import { mockPosts } from "@/lib/mockData";
import { useQuery } from "@tanstack/react-query";

interface Post {
  id: string;
  title: string;
  slug: string;
  content: string;
  excerpt?: string;
  coverImage?: string;
  published: boolean;
  createdAt: string;
  author: {
    id: string;
    name: string;
  };
  tags: Array<{
    id: string;
    name: string;
  }>;
}

export default function PostsPage() {
  const {
    data: posts = [],
    isLoading,
    isError,
    error,
  } = useQuery({
    queryKey: ["posts"],
    queryFn: () => apiRequest<Post[]>(API_ENDPOINTS.POSTS),
    retry: 1,
  });

  // 兼容 mock 数据逻辑
  const [useMockData, setUseMockData] = useState(false);
  const [mocked, setMocked] = useState<Post[]>([]);
  useEffect(() => {
    if (isError) {
      setUseMockData(true);
      setMocked(mockPosts);
    }
  }, [isError]);

  const formatDate = (dateString: string) => {
    return new Date(dateString).toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "long",
      day: "numeric",
    });
  };

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-gray-600">加载中...</p>
        </div>
      </div>
    );
  }

  if (isError && !useMockData) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <p className="text-red-500">
            获取文章列表失败:{" "}
            {error instanceof Error ? error.message : "未知错误"}
          </p>
        </div>
      </div>
    );
  }

  const renderPosts = useMockData ? mocked : posts;

  return (
    <div className="min-h-screen bg-gray-50">
      <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
        <div className="mb-8">
          <h1 className="text-3xl font-bold text-gray-900 mb-2">文章列表</h1>
          <p className="text-gray-600">发现精彩的文章内容</p>
          {useMockData && (
            <div className="mt-2 p-3 bg-yellow-50 border border-yellow-200 rounded-md">
              <p className="text-sm text-yellow-800">
                📝 当前显示的是演示数据，后端 API 可能未启动
              </p>
            </div>
          )}
        </div>

        {renderPosts.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-gray-500 text-lg">暂无文章</p>
          </div>
        ) : (
          <div className="grid gap-6 md:grid-cols-2 lg:grid-cols-3">
            {renderPosts.map((post) => (
              <Card key={post.id} className="hover:shadow-lg transition-shadow">
                {post.coverImage && (
                  <div className="aspect-video overflow-hidden rounded-t-lg">
                    <img
                      src={post.coverImage}
                      alt={post.title}
                      className="w-full h-full object-cover"
                    />
                  </div>
                )}
                <CardHeader>
                  <div className="flex items-center gap-2 mb-2">
                    <User className="h-4 w-4 text-gray-400" />
                    <span className="text-sm text-gray-500">
                      {post.author.name}
                    </span>
                    <Calendar className="h-4 w-4 text-gray-400 ml-2" />
                    <span className="text-sm text-gray-500">
                      {formatDate(post.createdAt)}
                    </span>
                  </div>
                  <CardTitle className="line-clamp-2">
                    <Link
                      href={`/posts/${post.slug}`}
                      className="hover:text-blue-600"
                    >
                      {post.title}
                    </Link>
                  </CardTitle>
                  {post.excerpt && (
                    <CardDescription className="line-clamp-3">
                      {post.excerpt}
                    </CardDescription>
                  )}
                </CardHeader>
                <CardContent>
                  {post.tags.length > 0 && (
                    <div className="flex items-center gap-2 mb-4">
                      <Tag className="h-4 w-4 text-gray-400" />
                      <div className="flex flex-wrap gap-1">
                        {post.tags.map((tag) => (
                          <Badge
                            key={tag.id}
                            variant="secondary"
                            className="text-xs"
                          >
                            {tag.name}
                          </Badge>
                        ))}
                      </div>
                    </div>
                  )}
                  <Link href={`/posts/${post.slug}`}>
                    <Button variant="outline" className="w-full">
                      阅读全文
                    </Button>
                  </Link>
                </CardContent>
              </Card>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
